﻿#region Imported Libraries
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using org.webguvenligi.NSecureImageLib.GraphicFileFormats.Utilities;
#endregion

namespace org.webguvenligi.NSecureImageLib.GraphicFileFormats.JPEG
{
    public class JpegChunkSOS : JPEGBaseChunk
    {
        public JpegChunkSOS(BinaryReader imageReader, ushort streamLength, string segmentName)
            : base(imageReader, streamLength, segmentName)
        {
        }
        protected override void ExtractBodyFromStream(BinaryReader imageReader,
                                                      ushort segmentLength)
        {
            
            MemoryStream markerStream = 
                new MemoryStream();

            long totalLength = 0;
            while (imageReader.BytesRemaining() > 0)
            {
                imageReader.EnsureBytes(1);
                byte currentElement =
                    imageReader.ReadByte();
                totalLength++;
                markerStream.WriteByte(currentElement);
                if (currentElement == 0xFF)
                {
                    imageReader.EnsureBytes(1);
                    byte nextElement =
                        imageReader.ReadByte();
                    totalLength++;
                    if (nextElement == 0xD9)
                    {
                        markerStream.Flush();
                        //We Detected End Header So Fallback 2 Bytes,
                        //To The Begin Of Segment And Exit
                        imageReader.BaseStream.Position -= 2;
                        break;
                    }
                    else
                    {
                        markerStream.WriteByte(nextElement);
                    }
                }
            }
            using (BinaryReader markerReader = new BinaryReader(markerStream))
            {
                ParseContent(markerReader);
            }
        }
        protected override void ParseContent(System.IO.BinaryReader contentReader)
        {
            
        }
    }
}
